package com.tianxinweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.tianxinweb.config.UploadConfig;
import com.tianxinweb.entity.BankCard;
import com.tianxinweb.entity.RechargeRecord;
import com.tianxinweb.entity.User;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import com.tianxinweb.mapper.UserMapper;
import com.tianxinweb.service.BankCardService;
import com.tianxinweb.service.RechargeRecordService;
import com.tianxinweb.service.UserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tianxinweb.utils.IdGen;
import com.tianxinweb.utils.ImageUtil;
import com.tianxinweb.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cboy
 * @since 2018-08-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UploadConfig uploadConfig;
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private BankCardService bankCardService;

    @Override
    public User getUserByPhone(String telphone) {
        return selectOne(new EntityWrapper<User>().eq("telphone",telphone));
    }


    @Override
    @Transactional
    public Integer addUser(User user) {
        User saveUser = new User();
        saveUser.setNickname(user.getNickname());
        saveUser.setTelphone(user.getTelphone());
        String loginSalt = IdGen.getRandomString(16);
        saveUser.setLoginPwd(Md5Util.generate(user.getLoginPwd(),loginSalt));
        saveUser.setLoginSalt(loginSalt);
        String  paySalt = IdGen.getRandomString(16);
        saveUser.setPayPwd(Md5Util.generate(user.getPayPwd(),paySalt));
        saveUser.setPaySalt(paySalt);
        saveUser.setUniqueCode(Md5Util.MD5(IdGen.getRandomString(16)));
		saveUser.setIdcard(user.getIdcard());

        if(user.getInviteCode() != null){
            //当邀请码不为空的时候获取该邀请码的用户
            User inviteUser = selectOne(new EntityWrapper<User>()
                    .setSqlSelect("uid")
                    .eq("invite_code",user.getInviteCode()));
            if(inviteUser!=null){
                //更新用户的下级人数
                updateForSet("lower_numb=lower_numb+1",new EntityWrapper<User>().eq("uid",inviteUser.getUid()));
                saveUser.setFatherId(inviteUser.getUid());
            }
        }
        insert(saveUser);
        saveUser.setInviteCode((saveUser.getUid()+1000)+"");
        updateById(saveUser);
        return saveUser.getUid();
    }

    @Override
    public void editUserImg(Integer userId, String path) {
        User user = new User();
        user.setUid(userId);

        String newPath = ImageUtil.moveFile(uploadConfig.getPath() + "/temp/" + path,
                uploadConfig.getPath() + "/profile/");
        user.setImgurl("/profile/"+newPath);
        updateById(user);
    }

    @Override
    public void editLoginPwd(Integer userId, String oldPwd, String newPwd) {
        User user = selectById(userId);
        if(!user.getLoginPwd().equals(Md5Util.generate(oldPwd,user.getLoginSalt()))){
            throw new MyException(ResultEnum.OLDPWD_ERROR);
        }
        user.setLoginPwd(Md5Util.generate(newPwd,user.getLoginSalt()));
        updateById(user);
    }

    @Override
    public void editPayPwd(User user, String newPwd) {
        user.setPayPwd(Md5Util.generate(newPwd,user.getPaySalt()));
        updateById(user);
    }

    @Override
    public List<User> getInvitationList(String uniqueCode, Integer userId) {
        //如果用户为空则直接获取用户的下级
        if(uniqueCode==null || "".equals(uniqueCode.trim())){
            List<User> users = selectList(new EntityWrapper<User>()
                    .setSqlSelect("uid", "nickname", "account", "lower_numb")
                    .eq("father_id", userId)
                    .orderBy("uid", false)
            );
            return users;
        }else{
            User user = selectOne(new EntityWrapper<User>().setSqlSelect("uid").eq("unique_code", uniqueCode));
            if(user==null) return null;
            List<User> users = selectList(new EntityWrapper<User>()
                    .setSqlSelect("uid", "nickname", "account", "lower_numb")
                    .eq("father_id", user.getUid())
                    .orderBy("uid", false)
            );
            return users;
        }
    }

    @Override
    public User getUserByPhoneOrUid(String account) {
        return selectOne(new EntityWrapper<User>()
                .eq("uid",account)
                .or("telphone={0}",account)
        );
    }

    @Override
    @Transactional
    public void recharge(Integer uid, Integer adminId, Integer num, Integer type, BigDecimal money) {
        User user = selectById(uid);
        if(user==null) throw new MyException(ResultEnum.USER_NOT_EXIST);
        //插入记录
        RechargeRecord rechargeRecord = new RechargeRecord();

        //充值类型，默认为0表示黑金币，1表示种子币，2表示注册金，3表示购币金
        if(type==0){
            if(num==null) throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
            rechargeRecord.setRechargeType(0);
            rechargeRecord.setNumber(num);
            rechargeRecord.setRechargeDesc("给"+user.getNickname()+"充值"+num+"枚黑金币");
            //用户金币添加
            updateForSet("black_coin=black_coin+"+num,new EntityWrapper<User>().eq("uid",uid));
        }else if(type==1){
            if(num==null) throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
            rechargeRecord.setRechargeType(1);
            rechargeRecord.setNumber(num);
            rechargeRecord.setRechargeDesc("给"+user.getNickname()+"充值"+num+"枚种子币");
            //用户金币添加
            updateForSet("seed_coin=seed_coin+"+num,new EntityWrapper<User>().eq("uid",uid));
        }else if(type==2){
            if(money==null){
                throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
            }
            rechargeRecord.setRechargeType(2);
            rechargeRecord.setRechargeMoney(money);
            rechargeRecord.setRechargeDesc("给"+user.getNickname()+"充值"+money+"注册金");
            //用户金币添加
            updateForSet("register_money=register_money+"+money,new EntityWrapper<User>().eq("uid",uid));
        }else{
            if(money==null){
                throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
            }
            rechargeRecord.setRechargeType(3);
            rechargeRecord.setRechargeMoney(money);
            rechargeRecord.setRechargeDesc("给"+user.getNickname()+"充值"+money+"购金币");
            //用户金币添加
            updateForSet("purchase_money=purchase_money+"+money,new EntityWrapper<User>().eq("uid",uid));
        }

        rechargeRecord.setAdminId(adminId);
        rechargeRecord.setUserId(uid);
        rechargeRecordService.insert(rechargeRecord);
    }

    @Override
    public Page getUserList(Integer pn, Integer size, String key) {
        if("".equals(key.trim())){
            return selectPage(new Page<>(pn,size,"uid",false),
                    new EntityWrapper<User>().setSqlSelect("uid","nickname","telphone","invite_code",
                            "father_id","register_time","account","black_coin","ustatus","imgurl",
                            "lower_numb","unique_code","seed_coin","register_money","purchase_money","idcard"));
        }else{
            return selectPage(new Page<>(pn,size,"uid",false),
                    new EntityWrapper<User>().setSqlSelect("uid","nickname","telphone","invite_code",
                            "father_id","register_time","account","black_coin","ustatus","imgurl",
                            "lower_numb","unique_code","seed_coin","register_money","purchase_money","idcard")
                            .eq("uid",key).or("nickname like {0}","%"+key+"%"));
        }
    }

    @Override
    public User getUserDetail(Integer id) {
        User user = selectById(id);
        List<BankCard> bankCards = bankCardService.selectList(new EntityWrapper<BankCard>().eq("user_id", user.getUid()));
        user.setBankCardList(bankCards);
        List<User> userList = selectList(new EntityWrapper<User>().eq("father_id", user.getUid()));
        user.setUserList(userList);
        return user;
    }

    @Override
    public List<User> getUserRelation(Integer id) {
        return selectList(new EntityWrapper<User>()
                .setSqlSelect("uid","nickname", "account", "lower_numb")
                .eq("father_id",id)
        );
    }

    @Override
    @Transactional
    public void deleteUserRelation(Integer id) {
        User user = selectById(id);
        if(user.getFatherId()==0) throw new MyException(ResultEnum.RELATION_ERROR);
        if(user==null) throw new MyException(ResultEnum.USER_NOT_EXIST);
        User user1 = selectOne(new EntityWrapper<User>().eq("father_id", user.getUid()));
        if(user1 != null) throw new MyException(ResultEnum.RELATION_ERROR);
        //父级的下级人数-1
        updateForSet("lower_numb=lower_numb-1",new EntityWrapper<User>().eq("uid",user.getFatherId()));

        user.setFatherId(0);
        updateById(user);
    }

    @Override
    @Transactional
    public void updateUser(User user) {

        User saveUser = selectById(user.getUid());
        saveUser.setNickname(user.getNickname());
        saveUser.setTelphone(user.getTelphone());
        if(user.getLoginPwd() != null && !"".equals(user.getLoginPwd().trim())){
            String loginSalt = IdGen.getRandomString(16);
            saveUser.setLoginPwd(Md5Util.generate(user.getLoginPwd(),loginSalt));
            saveUser.setLoginSalt(loginSalt);
        }
        if(user.getPayPwd() != null && !"".equals(user.getPayPwd().trim())){
            String  paySalt = IdGen.getRandomString(16);
            saveUser.setPayPwd(Md5Util.generate(user.getPayPwd(),paySalt));
            saveUser.setPaySalt(paySalt);
        }
        saveUser.setIdcard(user.getIdcard());

        if(user.getInviteCode() != null){
            //当邀请码不为空的时候获取该邀请码的用户
            User inviteUser = selectOne(new EntityWrapper<User>()
                    .setSqlSelect("uid")
                    .eq("invite_code",user.getInviteCode()));
            if(inviteUser!=null){
                //更新用户的下级人数
                if(saveUser.getFatherId() != inviteUser.getUid()){
                    updateForSet("lower_numb=lower_numb+1",new EntityWrapper<User>().eq("uid",inviteUser.getUid()));
                    updateForSet("lower_numb=lower_numb-1",new EntityWrapper<User>().eq("uid",saveUser.getFatherId()));
                    saveUser.setFatherId(inviteUser.getUid());
                }
            }else{
                saveUser.setFatherId(0);
            }
        }
        updateById(saveUser);
    }
}
